const HANDLES = {};

function on(name, handle) {
  if (!name || typeof name !== 'string' || typeof handle !== 'function') {
    return;
  }
  if (!Array.isArray(HANDLES[name])) {
    HANDLES[name] = [];
  }
  HANDLES[name].push(handle);
  // console.log(handle[key]);
  // console.log('listener on HANDLES: ', HANDLES);
}

function off(name, handle) {
  if (!name || !HANDLES[name] || !HANDLES[name].length) {
    return;
  }
  if (handle === undefined) {
    HANDLES[name].length = 0;
    return;
  }
  if (typeof handle === 'function') {
    let index = HANDLES[name].indexOf(handle);
    if (index > -1) {
      HANDLES[name].splice(index, 1);
    }
  }
  // console.log('listener off HANDLES: ', HANDLES);
}

async function emit(name, data) {
  if (!name || !HANDLES || !HANDLES[name] || !HANDLES[name].length) {
    return [];
  }
  let result = await Promise.all(
    HANDLES[name].map(async (handle) => {
      return typeof handle === 'function' ? await handle(data) : null;
    }),
  );
  return result.filter((item) => item !== undefined && item !== null);
}

export default { on, off, emit };
